//
//  WJPDFSignatureView.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/23.
//

import UIKit
import SnapKit

import UIKit
import SnapKit

protocol WJPDFSignatureBoxViewDelegate: AnyObject {
    /// 签名框被点击
    func signatureBoxTapped(_ signatureBox: WJPDFSignatureBoxView)
    /// 签名被清除
    func signatureBoxCleared(_ signatureBox: WJPDFSignatureBoxView)
}

extension WJPDFSignatureBoxViewDelegate {
    func signatureBoxTapped(_ signatureBox: WJPDFSignatureBoxView) { }
    func signatureBoxCleared(_ signatureBox: WJPDFSignatureBoxView) { }
}

class WJPDFSignatureBoxView: UIView {

    // 签名图像
    var signatureImage: UIImage? {
        didSet {
            signatureImageView.image = signatureImage
        }
    }
    
    // 签名图像视图
    private let signatureImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.backgroundColor = .clear
        imageView.isUserInteractionEnabled = false
        return imageView
    }()
    
    // 边框视图
    private let borderView: UIView = {
        let view = UIView()
        view.layer.borderWidth = 2
        view.layer.borderColor = UIColor(hex: "#1F87F6").cgColor
        view.backgroundColor = .clear
        view.layer.cornerRadius = 4
        view.layer.masksToBounds = true
        return view
    }()
    
    // 清除按钮
    private let clearButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "box_delete_icon"), for: .normal)
        button.backgroundColor = .clear
        return button
    }()
    
    // 缩放按钮（右下角 - 等比缩放）
    private let resizeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "box_zoom_icon"), for: .normal)
        button.backgroundColor = .clear
        return button
    }()
    
    // 移动按钮（左上角 - 拖动移动）
    private let moveButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "box_move_icon"), for: .normal)
        button.backgroundColor = .clear
        return button
    }()
    
    // 签名代理
    weak var delegate: WJPDFSignatureBoxViewDelegate?
    
    // 手势状态
    private var isDragging = false
    private var isResizing = false
    private var isMoving = false
    
    // 触摸起点和初始状态
    private var touchStartPoint: CGPoint = .zero
    private var initialCenter: CGPoint = .zero
    private var initialBounds: CGRect = .zero
    private var initialTransform: CGAffineTransform = .identity
    
    // 最小尺寸限制
    private let minSize: CGSize = CGSize(width: 50, height: 50)
    
    // 是否选中
    private var isSelected: Bool = true {
        didSet {
            updateSelectionState()
        }
    }
    
    // MARK: - 初始化
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
        setupGestures()
        setupButtons()
        setSelected(true)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
        setupGestures()
        setupButtons()
        setSelected(true)
    }

    // MARK: - 视图设置
    private func setupView() {
        backgroundColor = .clear
        
        addSubview(borderView)
        addSubview(signatureImageView)
        
        borderView.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(12)
        }
        
        signatureImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(0)
        }
    }
    
    private func setupButtons() {
        addSubview(clearButton)
        addSubview(resizeButton)
        addSubview(moveButton)
        
        clearButton.addTarget(self, action: #selector(clearButtonTapped), for: .touchUpInside)
        
        // 左上角按钮 - 拖动移动
        let movePanGesture = UIPanGestureRecognizer(target: self, action: #selector(handleMovePanGesture(_:)))
        moveButton.addGestureRecognizer(movePanGesture)
        
        // 右下角按钮 - 等比缩放
        let resizePanGesture = UIPanGestureRecognizer(target: self, action: #selector(handleResizePanGesture(_:)))
        resizeButton.addGestureRecognizer(resizePanGesture)
        
        // 按钮约束
        clearButton.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.trailing.equalToSuperview()
            make.width.height.equalTo(24)
        }
        
        moveButton.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalToSuperview()
            make.width.height.equalTo(24)
        }
        
        resizeButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.trailing.equalToSuperview()
            make.width.height.equalTo(24)
        }
    }
    
    private func setupGestures() {
        // 整体拖动手势
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
        addGestureRecognizer(panGesture)
        
        // 点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
        tapGesture.numberOfTapsRequired = 1
        addGestureRecognizer(tapGesture)
    }
    
    // MARK: - 手势处理
    
    @objc private func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: superview)
        
        switch gesture.state {
        case .began:
            isDragging = true
            touchStartPoint = gesture.location(in: superview)
            initialCenter = center
            bringSubviewToFront(self)
            setSelected(true)
        case .changed:
            if isDragging {
                center = CGPoint(
                    x: initialCenter.x + translation.x,
                    y: initialCenter.y + translation.y
                )
            }
        case .ended, .cancelled:
            isDragging = false
        default:
            break
        }
    }
    
    // 左上角按钮 - 拖动移动
    @objc private func handleMovePanGesture(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: superview)
        
        switch gesture.state {
        case .began:
            isMoving = true
            touchStartPoint = gesture.location(in: superview)
            initialCenter = center
            bringSubviewToFront(self)
            setSelected(true)
            
        case .changed:
            if isMoving {
                // 直接移动整个视图
                center = CGPoint(
                    x: initialCenter.x + translation.x,
                    y: initialCenter.y + translation.y
                )
            }
            
        case .ended, .cancelled:
            isMoving = false
            
        default:
            break
        }
    }
    
    @objc private func handleResizePanGesture(_ gesture: UIPanGestureRecognizer) {
        let location = gesture.location(in: superview)
        
        switch gesture.state {
        case .began:
            isResizing = true
            touchStartPoint = location
            initialBounds = bounds
            initialCenter = center
            initialTransform = transform
            bringSubviewToFront(self)
            setSelected(true)

        case .changed:
            if isResizing {
                // 计算从初始触摸点到当前点的向量
                let deltaX = location.x - touchStartPoint.x
                let deltaY = location.y - touchStartPoint.y
                
                // 基于对角线方向的移动来计算缩放比例
                // 使用更稳定的计算方法：基于初始宽高的比例
                let scaleX = 1.0 + deltaX / initialBounds.width * 3
                let scaleY = 1.0 + deltaY / initialBounds.height * 3
                
                // 取平均值或最小值来保持等比缩放
                let scaleFactor = max(0.1, (scaleX + scaleY) / 2) // 使用平均值，确保最小缩放为0.1
                
                // 应用新的尺寸（保持等比）
                let newWidth = max(minSize.width, initialBounds.width * scaleFactor)
                let newHeight = max(minSize.height, initialBounds.height * scaleFactor)
                
                // 更新bounds
                bounds = CGRect(x: 0, y: 0, width: newWidth, height: newHeight)
                
                center = initialCenter
            }
            
        case .ended, .cancelled:
            isResizing = false
            
        default:
            break
        }
    }
    
    @objc private func handleTapGesture(_ gesture: UITapGestureRecognizer) {
        setSelected(true)
        delegate?.signatureBoxTapped(self)
    }
    
    // MARK: - 按钮事件
    
    @objc private func clearButtonTapped() {
        signatureImage = nil
        delegate?.signatureBoxCleared(self)
    }
    
    // MARK: - 选中状态管理
    
    private func updateSelectionState() {
        clearButton.isHidden = !isSelected
        moveButton.isHidden = !isSelected
        resizeButton.isHidden = !isSelected
        borderView.isHidden = !isSelected
    }
    
    // MARK: - 公共方法
    
    func setSignatureImage(_ image: UIImage?) {
        signatureImage = image
    }
    
    func getSignatureImage() -> UIImage? {
        return signatureImage
    }
    
    func setSelected(_ selected: Bool) {
        isSelected = selected
    }
    
    func getSelected() -> Bool {
        return isSelected
    }
    
    func toggleSelection() {
        isSelected = !isSelected
    }
    
    /// 获取当前缩放比例
    func getCurrentScale() -> CGFloat {
        return bounds.width / minSize.width
    }
    
    /// 获取当前旋转角度（简化版本，移除旋转功能）
    func getCurrentRotation() -> CGFloat {
        return 0.0 // 由于移除了旋转功能，固定返回0
    }
}

